package com.brush.brushcommon.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.brush.brushcommon.common.sys.pojo.PartyGroupConfig;
import com.brush.brushcommon.common.sys.service.PartyGroupConfigService;
import jakarta.annotation.PostConstruct;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.List;

/**
 * 阿里OSS工具类
 * @Author cws
 */
@Log4j2
@Component
public class OSSUtil {

    @Autowired
    PartyGroupConfigService partyGroupConfigService;
    @Autowired
    private Environment environment;

    /** accessId **/
    private static String accessId;
    /** accessKey **/
    private static String accessKey;
    /** bucket名称 如：arpa-ntocc **/
    private static String bucketName;
    /** 终端节点 如：oss-cn-beijing.aliyuncs.com **/
    private static String endpoint;

    /**
     * OSSClient 客户端
     */
    private static OSS client;

    /**
     * 初始化配置
     */
    @PostConstruct
    public void initConfig() {
        try {
            PartyGroupConfig fileUploadTypeConfig = partyGroupConfigService.getOne(new QueryWrapper<PartyGroupConfig>().lambda()
                    .eq(PartyGroupConfig::getType,"fileUploadType").eq(PartyGroupConfig::getConfigKey,"fileUploadType"),false);
            if(fileUploadTypeConfig!=null && "oss".equals(fileUploadTypeConfig.getConfigValue())){
                List<PartyGroupConfig> configList = partyGroupConfigService.list(new QueryWrapper<PartyGroupConfig>().lambda().eq(PartyGroupConfig::getType,"OSS"));
                if(CollectionUtils.isEmpty(configList)){
                    log.error(LogUtil.log("++阿里OSS配置缺失，请检查配置。++"));
                }
                for(PartyGroupConfig config:configList){
                    switch (config.getConfigKey()){
                        case "accessId": accessId=config.getConfigValue(); break;
                        case "accessKey": accessKey=config.getConfigValue(); break;
                        case "bucketName": bucketName=config.getConfigValue(); break;
                        case "endpoint": endpoint=config.getConfigValue(); break;
                        default:
                    }
                }
                // 创建OSSClient实例
                client = new OSSClientBuilder().build(endpoint, accessId, accessKey);
                log.info(LogUtil.log("++阿里OSS配置初始化完毕++"));
            }
        } catch (Exception e) {
            log.error("catch Exception",e);
        }
    }

    /**
     * 上传文件
     * @param myFile
     */
    public static String uploadFile(MultipartFile myFile) {
        if( null==myFile ){
            return "";
        }
        String filePath="";
        try {
            String key = generateFileKey(myFile);
            ObjectMetadata objectMeta = new ObjectMetadata();
            objectMeta.setContentLength(myFile.getSize());
            // 可以在metadata中标记文件类型
            objectMeta.setContentType(myFile.getContentType());
            client.putObject(bucketName, key, myFile.getInputStream(), objectMeta);
            filePath = getFilePath(key);
            log.info(LogUtil.log("upFile","上传oss文件："+filePath));
        } catch (Exception e) {
            log.error("catch Exception",e);
        }
        return filePath;
    }

    /**
     * 上传文件
     * @param inputStream 文件流
     * @param suffix 文件后缀，如： jpg
     * @return
     */
    public static String uploadFile(InputStream inputStream,String suffix) {
        String filePath="";
        try {
            String key = IdUtil.simpleUUID()+"."+suffix;
            //统一文件到日文件夹
            String month= DateUtil.today();
            key=month+"/"+key;
            client.putObject(bucketName, key, inputStream);
            filePath = getFilePath(key);
            log.info(LogUtil.log("upFile","上传oss文件："+filePath));
        }catch (Exception e) {
            log.error("catch Exception",e);
        }
        return filePath;
    }


    /**
     * 上传文件
     * @param file
     */
    public static String uploadFile(File file) {
        if( null==file ){
            return "";
        }
        String filePath="";
        try {
            String fileName = file.getName();
            //转义拆分重命名文件
            String[] strArr=fileName.split("\\.");
            String type = strArr[strArr.length-1];
            String key = IdUtil.simpleUUID()+"."+ type;
            //统一文件到日文件夹
            String month= DateUtil.today();
            key=month+"/"+key;
            InputStream inputStream = new FileInputStream(file);
            client.putObject(bucketName, key, inputStream);
            filePath = getFilePath(key);
            log.info(LogUtil.log("upFile","上传oss文件："+filePath));
        }catch (Exception e) {
            log.error("catch Exception",e);
        }
        return filePath;
    }

    /**
     * 下载文件到本地临时
     * @param key 如： 2020-04-07/48068d34051a48afb7b5365ecd369e25.png
     * @return
     */
//    public static File downloadFile(String key) {
//        String fileFullPath = fileTempPath+key;
//        File filePath = new File(fileFullPath.substring(0,fileFullPath.lastIndexOf("/")));
//        if(!filePath.exists()){
//            filePath.mkdirs();
//        }
//        File file = new File(fileFullPath);
//        try {
//            // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
//            client.getObject(new GetObjectRequest(bucketName, key), file);
//            log.info(LogUtil.log("downloadFile","下载oss文件："+file.getAbsolutePath()));
//        }catch (Exception e) {
//            log.error("catch Exception",e);
//            return null;
//        }
//        return file;
//    }

    /**
     * 生成文件唯一key
     * @param myFile
     */
    private static String generateFileKey(MultipartFile myFile){
        log.info(LogUtil.log("upFile","源文件。文件长度："+myFile.getSize()+",文件类型："+myFile.getContentType()+",文件原名："+myFile.getOriginalFilename()));
        String fileName = myFile.getOriginalFilename();
        //转义拆分重命名文件
        String[] strArr=fileName.split("\\.");
        String type = strArr[strArr.length-1];
        String key = IdUtil.simpleUUID()+"."+ type;
        //统一文件到日文件夹
        String month= DateUtil.today();
        key=month+"/"+key;
        return key;
    }

    /**
     * 获取文件路径
     * @param key 如： 2020-04-07/48068d34051a48afb7b5365ecd369e25.png
     * @return
     */
    private static String getFilePath(String key) {
        String filePath="";
        try {
            //阿里oss必须设置链接失效时间
            Date expiration = new Date(System.currentTimeMillis() + 1000 * 60);
            URL url = client.generatePresignedUrl(bucketName, key, expiration);
            if (null == url) {
                return null;
            }
            filePath = url.toString();
            //生成的链接是带有失效时间的，这里去掉失效时间，保留永久链接地址 如：http://arpa-ntocc.oss-cn-beijing.aliyuncs.com/2020-04-13/7fb98200b1fb48a7a741eea92cb4d798.png?Expires=1586745836&OSSAccessKeyId=qzSGmi1ntjgOWG5q&Signature=vIVp0zHGXW%2BqtGAEVXdp08MjTeE%3D
            if (!StringUtils.isEmpty(filePath)) {
                int index = filePath.indexOf("?");
                if (index > 0) {
                    filePath = filePath.substring(0, index);
                }
            }

        } catch (Exception e) {
            log.error("catch Exception",e);
        }
        return filePath;
    }


}
